package com.test.list.contacts;

/** Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
import java.util.ArrayList;
import java.util.Hashtable;

import com.test.list.classes.ViewableList;
import com.test.list.interfaces.Viewable;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

public class ContactMngr
{
	private static ContactMngr mInstance;
	private static Context mContext;

	public static final ViewableList mLoadedViewablesAsc = new ViewableList();
	public final static String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
	public final static String DISPLAY_ID = ContactsContract.Contacts._ID;
	public final static String PHOTO_ID = ContactsContract.Contacts.PHOTO_ID;
	public final static String LOOKUP_KEY = ContactsContract.Contacts.LOOKUP_KEY;

	public static ContactMngr getInstance()
	{
		ContactMngr retVal = mInstance;
		if (mInstance == null)
		{
			retVal = new ContactMngr();
		}

		return retVal;
	}

	private ContactMngr()
	{
		super();
	}

	public void loadViewableList()
	{
		mLoadedViewablesAsc.clear();
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		ContentResolver cr = mContext.getContentResolver();
		String sortOrder = DISPLAY_NAME + " COLLATE LOCALIZED ASC";
		String[] columns = new String[]
		{ DISPLAY_ID, DISPLAY_NAME, LOOKUP_KEY };// PHOTO_ID,
		String[] arrayOfString = new String[1];
		arrayOfString[0] = "1";
		final Cursor cur = cr.query(uri, columns, "has_phone_number=?",
				arrayOfString, sortOrder);
		try
		{
			if (cur.getCount() > 0)
			{
				String id;
				String name;
				String lookUpKey;
				// String photoId;
				while (cur.moveToNext())
				{
//					lookUpKey = cur.getString(3);
					id = cur.getString(0);
					name = cur.getString(1);
					// photoId = cur.getString(2);
					lookUpKey = cur.getString(2);
					DeviceContact c = new DeviceContact(id, name, lookUpKey);// photoId, );
					mLoadedViewablesAsc.addViewable(c);
				}
			}
		} catch (Exception e)
		{
		} finally
		{
			cur.close();
		}
	}

	public Uri getContactPhotoUri(long contactId)
	{
		Uri photoUri = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI, contactId);
		photoUri = Uri.withAppendedPath(photoUri,
				ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

		return photoUri;
	}
	
	public ViewableList getContacts(String constraint)
	{
		ViewableList retVal = null;
		retVal = getBaseContactList(constraint);

		return retVal;
	}

	private ViewableList getBaseContactList(String constraint)
	{
		if (constraint == null)
		{
			return mLoadedViewablesAsc;
		}
		ViewableList list = new ViewableList();
		for (Viewable viewable : mLoadedViewablesAsc.getViewables())
		{
			if (viewable.getMainHeader().contains(constraint))
			{
				list.addViewable(viewable);
			}
		}

		return list;
	}

	public void setContext(Context applicationContext)
	{
		mContext = applicationContext;
	}

	/**
	 * 
	 * @param ctx
	 * @param resultCode
	 * @param prefs
	 * @param c
	 * @param columnsToSelect
	 * @return
	 */
	public Hashtable<String, String> select(Context ctx, int resultCode,
			Cursor c, ArrayList<String> columnsToSelect)
	{
		Hashtable<String, String> retVal = new Hashtable<String, String>();
		ContentResolver cr = ctx.getContentResolver();
		if (c.moveToFirst())
		{
			String id = c.getString(c
					.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
			retVal.put(ContactsContract.Contacts._ID + " " + "ANGEL", id);
			try
			{
				int colIndex = c
						.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
				if (Integer.parseInt(c.getString(colIndex)) > 0)
				{
					Cursor pCur = cr.query(
							ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
							null,
							ContactsContract.CommonDataKinds.Phone.CONTACT_ID
									+ "=?", new String[]
							{ id }, null);
					if (pCur != null)
					{
						boolean isFirstRun = true;
						while (pCur.moveToNext())
						{

							// Do something with phones
							for (int i = 0; i < columnsToSelect.size(); i++)
							{
								String igetted = columnsToSelect.get(i);
								if (igetted == ContactsContract.CommonDataKinds.Phone.NUMBER)
								{
									int type = pCur
											.getInt(pCur
													.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

									String s = pCur
											.getString(pCur
													.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
									retVal.put(
											ContactsContract.CommonDataKinds.Phone.NUMBER
													+ " " + type, s);
								} else if (igetted != ContactsContract.CommonDataKinds.Phone.NUMBER
										&& isFirstRun)
								{
									String pCurRetVal = pCur.getString(pCur
											.getColumnIndex(igetted));

									retVal.put(igetted, pCurRetVal);
								}

							}
							if (isFirstRun == true)
							{
								isFirstRun = false;
							}
						}
					}
					pCur.close();
				}
			} catch (Exception e)
			{
			}
		}

		return retVal;
	}

}